<template>
    <div class="alarmhistory">
        <div class="toparea">
            <p class="title">报警信息(清洗)</p>
            <div class="currenttime">{{ currentTime }}</div>
        </div>
        <div class="mainarea">
            <div class="searchcondition">
                <div class="processpick">
                    <p class="text">工序</p>
                    <el-select class="select" v-model="selectedArr" multiple collapse-tags placeholder="请选择">
                        <el-option label='全选' value='全选' @click.native='selectAll' v-if="options.length"></el-option>
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="linepick">
                    <p class="text">线体</p>
                    <el-select class="select" v-model="selectedArr1" multiple placeholder="请选择">
                        <el-option label='全选' value='全选' @click.native='selectAll1' v-if="options1.length"></el-option>
                        <el-option
                        v-for="item in options1"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="datepick">
                    <p class="text">起止日期</p>
                    <el-date-picker
                    class="select"
                    v-model="dateValue"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-value="timeDefaultShow"
                    :picker-options="pickerOptions">
                    </el-date-picker>
                </div>
                <el-button class="btn" type="primary" icon="el-icon-search" @click="searchAlarmHistory">查询</el-button>
                <el-button type="primary" @click="exportToExcel">导出<i class="el-icon-upload2 el-icon--right"></i></el-button>
            </div>
            <!-- <div class="tablearea"> -->
            <el-table
                class="alarmlist"
                stripe
                :data="alarmData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                :header-cell-style="{background:'#0d1543',color:'white',textAlign:'center'}"
                :cell-style="{background:'#0a1136',color:'white',textAlign: 'center'}"
                style="width: 88%"
                >
                <el-table-column
                    type="index"
                    label="序号"
                    width="70">
                </el-table-column>
                <el-table-column
                    prop="productionProcess"
                    label="工序"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="lineNumber"
                    label="线体"
                    width="90">
                </el-table-column>
                <el-table-column
                    prop="startAlarmTime"
                    label="报警开始时间"
                    width="220"
                    sortable
                >
                </el-table-column>
                <el-table-column
                    prop="endAlarmTime"
                    label="报警结束时间"
                    width="220"
                    sortable
                >
                </el-table-column>
                <el-table-column
                    prop="shutdownType"
                    label="停机类型"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="alarmDetails"
                    label="报警信息"
                    show-overflow-tooltip
                    >
                </el-table-column>
                <el-table-column
                    prop="alarmDuration"
                    label="报警时长/min"
                    width="160"
                    sortable
                >
                </el-table-column>
            </el-table>
            <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            layout="prev, pager, next,jumper, ->, total"
            :page-size="pageSize"
            :total="alarmData.length">
            </el-pagination>
            <!-- </div> -->
        </div>
    </div>
</template>
<style scoped>
.alarmhistory{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    background: url(../assets/backimg.jpeg) no-repeat center center;
    background-size: cover;
    background-position: center;
    z-index: -1;
    color: white;
}
.toparea{
    width: 100%;
    height: 3.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin-top: -3rem;
}
.title{
    position: absolute;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    padding: .5rem 3rem;
    border-radius: .5rem;
    background: #0d1543;
}
.currenttime{
    font-size: 1.25rem;
    position: absolute;
    right: 1.875rem;
}
.mainarea{
    width: 100%;
    height: 80%;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    margin-top: -2rem;
}
.searchcondition{
    width: 85%;
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.processpick, .linepick, .datepick{
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.text{
    font-size: 1.25rem;
    /* font-weight: bold; */
    color: rgba(41, 224, 227, 1);
}
.select{
    width: 13.75rem;
    margin-left: .75rem;
}
::v-deep .el-range-separator {
    width: 1.25rem !important;
}
.btn{
    margin-right: -1.5rem;
}
.tablearea{
    /* border: .125rem solid #0d1543; */
    width: 80%;
    height: 80%;
}
.alarmlist{
    /* max-height: 80%; */
    background-color: #0a1136;
    font-size: 1rem;
}
::v-deep .el-table th.el-table__cell {
    background-color: #0d1543;
}
.el-table::before {
    height: 0;
}
</style>
<script>
import axios from 'axios';
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
export default{
    mounted() {
        // this.initSortTable();
        this.startFlashing();
        // this.setDateRange();
        // this.dateTime()
    },
    data(){
        return{
            currentPage: 1, // 当前页码
            pageSize: 10, // 每一页显示的数据量
            dateValue:'',
            countss:0,
            timeDefaultShow:this.dateTime(),
            defaultTime:'',
            pickerOptions: {
                disabledDate: time => {
                    return new Date().getTime()< time.getTime() || (new Date().getTime()-3600*24*1000*365)>time.getTime()
                },
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
            currentTime: this.getCurrentDateTime(),
            options: [{
            value: '2',
            label: '烘烤工艺'
            }, {
            value: '3',
            label: '烘烤物流'
            },{
            value: '4',
            label: '封口焊'
            }, {
            value: '5',
            label: '二次氦检'
            }],
            options1: [{
            value: '1',
            label: '1线'
            }, {
            value: '2',
            label: '2线'
            }, {
            value: '3',
            label: '3线'
            }],
            selectedArr: [],
            selectedArr1: [],
            alarmData:[]
        }
    },
    methods:{
        // 处理当前页码变化事件
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
        },
        startFlashing() {
            this.intervalId = setInterval(() => {
                this.currentTime = this.getCurrentDateTime();
            }, 1000); // 每秒切换一次
        },
        getCurrentDateTime(){
            const now = new Date();
            return `${now.getFullYear()}-${this.padNumber(now.getMonth() + 1)}-${this.padNumber(now.getDate())}
            ${this.padNumber(now.getHours())}:${this.padNumber(now.getMinutes())}:${this.padNumber(now.getSeconds())}`;
        },
        padNumber(num) {
            return num < 10 ? '0' + num : num;
        },
        selectAll() {
            if (this.selectedArr.length < this.options.length) {
                this.selectedArr = []
                this.options.forEach((item) => {
                this.selectedArr.push(item.value)
                })
                // this.selectedArr.unshift('全选');
            } else {   // 取消全选
                this.selectedArr = [];
            }
        },
        selectAll1() {
            if (this.selectedArr1.length < this.options1.length) {
                this.selectedArr1 = []
                this.options1.forEach((item) => {
                this.selectedArr1.push(item.value)
                })
                // this.selectedArr.unshift('全选');
            } else {   // 取消全选
                this.selectedArr1 = [];
            }
        },
        dateTime(){
            this.defaultTime=new Date()
            this.defaultTime.setMonth(new Date().getMonth()-1)
            return this.defaultTime
        },
        // changeInitCalendarRange() {
        //     if(this.countss > 0) return;
        //         this.countss++

        //         let element = document.querySelector("button.el-picker-panel__icon-btn.el-icon-arrow-left");
        //         if (element) element.click();
        // },
        // onsetmonitor(){
        //     if(this.dateValue) return;
        //     this.countss = 0
        // },
        // setDateRange() {
        //     const end = new Date(); // 当前月第一天
        //     const start = new Date();
        //     start.setMonth(start.getMonth() - 1); // 上月第一天
        //     this.dateValue = [start, end]; // 设置日期范围为上月和本月
        // },
        searchAlarmHistory(){
            // alert('下个版本上线此功能')
            this.sendAndGetAlarmHist()
        },
        sendAndGetAlarmHist(){
            // 内置清除按钮清除时间后重新赋值
            if (!this.dateValue) {
                this.dateValue = []
            }
            if(this.selectedArr.length==0){
                this.$message({
                    message: '请选择至少一个工序！',
                    type: 'warning'
                })
            }
            else{
                if(this.selectedArr1.length==0){
                    this.$message({
                        message: '请选择至少一个线体！',
                        type: 'warning'
                    })
                }
                else{
                    if(this.dateValue[0]==undefined){
                        this.$message({
                            message: '请选择起止日期！',
                            type: 'warning'
                        })
                    }
                }
            }
            console.log('清洗历史报警查询条件：工序：',JSON.stringify(this.selectedArr)+'  线体：',JSON.stringify(this.selectedArr1)+'  开始日期：',this.dateValue[0]+'  结束日期：',this.dateValue[1])
            this.alarmData=[]
            this.currentPage = 1
            if(this.selectedArr.length>0 && this.selectedArr1.length>0 && this.dateValue[0]!==undefined && this.dateValue[1]!==undefined){
                axios.post('/myapp/monitor/queryWashedAlarm',{ processList:this.selectedArr,lineNumberList:this.selectedArr1,startDate:this.dateValue[0],endDate:this.dateValue[1] }).then(res=>{
                    console.log('清洗历史报警返回数据：',res.data)
                    if(res.data.data.length>0){
                        res.data.data.forEach(item=>{
                            item.startAlarmTime=item.startAlarmTime.substring(0,10)+' '+item.startAlarmTime.substring(11)
                            if(item.endAlarmTime!==null){
                                item.endAlarmTime=item.endAlarmTime.substring(0,10)+' '+item.endAlarmTime.substring(11)
                            }
                            if(item.productionProcess=='2'){
                            item.productionProcess='烘烤工艺'
                            }
                            if(item.productionProcess=='3'){
                            item.productionProcess='烘烤物流'
                            }
                            if(item.productionProcess=='4'){
                            item.productionProcess='封口焊'
                            }
                            if(item.productionProcess=='5'){
                            item.productionProcess='二次氦检'
                            }
                            if(item.lineNumber=='1'){
                            item.lineNumber='1线'
                            }
                            if(item.lineNumber=='2'){
                            item.lineNumber='2线'
                            }
                            if(item.lineNumber=='3'){
                            item.lineNumber='3线'
                            }
                            if(item.shutdownType=='2'){
                                item.shutdownType='主动停机'
                            }
                            if(item.shutdownType=='3'){
                                item.shutdownType='被动停机'
                            }
                            this.alarmData.push(item)
                        })
                    }
                    else{
                        this.$notify({
                            title: '提示',
                            message: '没有查询到报警信息',
                            // offset: 300,
                            type: 'success'
                        });
                    }
                })
            }
        },
        exportToExcel(){
            this.pageSize = this.alarmData.length
            this.currentPage = 1
            this.$nextTick(function() {
                // 获取表格的DOM元素
                const table = document.querySelector('.alarmlist');
                // 生成工作簿对象
                const wb = XLSX.utils.table_to_book(table);
                // 生成Excel文件
                const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' });
                try {
                    // 使用Blob进行导出
                    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '报警历史信息.xlsx');
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout);
                }
                this.pageSize = 10
                return wbout;
            })
        },
        initSortTable() {
            let sortField = [
                {
                multiOrder: "descending",
                property: "alarmdate",
                },
                // {
                // multiOrder: "descending",
                // property: "starttime",
                // },
                // {
                // multiOrder: "descending",
                // property: "endtime",
                // },
                // {
                // multiOrder: "descending",
                // property: "alarmduration",
                // }
            ];
            sortField.forEach((column) => {
                this.handleOrderChange(column);
            });
        },
        handleHeaderClass({ column }) {
            if (column.sortable == "custom") {
                if (column.multiOrder) {
                column.order = column.multiOrder;
                } else {
                column.order = column.sortOrders[1];
                }
            }
        },
        handleOrderChange(column) {
            if (column.multiOrder) {
                let table = JSON.parse(JSON.stringify(this.alarmData));
                if (column.multiOrder == "descending") {
                    console.log("1");
                    //降序
                table = table.sort((itemA, itemB) => {
                    //数字
                    if (!isNaN(itemA[column.property])) {
                    return itemB[column.property] - itemA[column.property];
                    //日期或字符串
                    } else {
                    let flag = itemA[column.property] > itemB[column.property];
                    return flag ? -1 : 1;
                    }
                });
                } else {
                    //升序
                table = table.sort((itemA, itemB) => {
                    if (!isNaN(itemA[column.property])) {
                    return itemA[column.property] - itemB[column.property];
                    } else {
                    let flag = itemA[column.property] < itemB[column.property];
                    return flag ? -1 : 1;
                    }
                });
                }
                this.alarmData = table;
            }
        },
        handleTableSort({ column }) {
            console.log(column)
            if (column.sortable !== "custom") {
                return;
            }
            if (!column.multiOrder) {
                column.multiOrder = "descending";
            } else if (column.multiOrder == "descending") {
                column.multiOrder = "ascending";
            } else if(column.multiOrder == "ascending") {
                column.multiOrder = "descending";
            }
            //具体排序操作
            this.handleOrderChange(column);
        },
    }
}
</script>